﻿#region Usings

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.Awesome.Mvc;
using Rail.Net.Common;
using Rail.Net.Common.Helpers;
using Rail.Net.Common.Model;

#endregion

namespace Rail.Net.Controllers
{
    public class FromStationLookupController : StationLookupController
    {
        public override ActionResult SearchForm()
        {
            return PartialView();
        }

        public override ActionResult Header()
        {
            return PartialView();
        }

        public ActionResult Search(string searchTerm, string toStationEva, int? page = null)
        {
            string toStation = null;
            // get text from the TO STATIONS LIST
            if (!String.IsNullOrEmpty(toStationEva))
            {
                var cookie = Session[Constants.ToStationsCookie] as string;
                if (cookie != null)
                {
                    var list = JsonHelper.Deserialize<List<NameValuePair>>(cookie);
                    toStation = list.FirstOrDefault(item => item.Value == toStationEva).Name;
                }
            }
            var src = StationLookupService.GetStations(searchTerm, toStation, true);


            // set a cookie for the results
            //var json = JsonHelper.Serialize(src);
            Session[Constants.FromStationsCookie] = src;

            if (page.HasValue)
            {
                const int pageSize = 10;
                var rows = this.RenderView(@"Awesome\LookupList", src.Skip((page.Value - 1)*pageSize).Take(pageSize));


                return Json(new {rows, more = src.Count() > page*pageSize});
            }
            return View(@"Awesome\LookupList", src);
        }

        //returns the text that is going to be set into the textbox near the lookup button 
        public ActionResult Get(string id)
        {
            var list = Session[Constants.FromStationsCookie] as List<NameValuePair>;
            if (list != null)
            {
                //var list = JsonHelper.Deserialize<List<NameValuePair>>(json);
                return Content(list.FirstOrDefault(item => item.Value == id).Name);
            }

            return Content("");
        }
    }
}